<template>
  <!-- 城市选择-->
  <view class="city-select">
    <scroll-view
        :scroll-top="scrollTop"
        scroll-y="true"
        class="city-select-main"
        id="city-select-main"
        :scroll-into-view="toView"
    >
      <!-- 预留搜索-->
      <view class="city-serach" v-if="isSearch">
        <view class="search_content">
          <icon type="search" size="18" class="city-serach-icon"/>
          <input
              @input="keyInput"
              :placeholder="placeholder"
              class="city-serach-input"
          />
        </view>
      </view>
      <!-- 当前定位城市 -->
      <!-- <view class="hot-title" v-if="activeCity && !serachCity">当前定位城市</view>
			<view class="hot-city" v-if="activeCity && !serachCity">
				<view class="hot-item" @click="cityTrigger(activeCity)">{{ activeCity[formatName] }}</view>
			</view> -->
      <!-- 热门城市 -->
      <view class="hot-title" v-if="hotCity.length > 0 && !serachCity"
      >申请单内城市
      </view
      >
      <view class="hot-city" v-if="hotCity.length > 0 && !serachCity">
        <template v-for="(item, index) in hotCity">
          <view :key="index" @click="cityTrigger(item)" class="hot-item">{{
              item[formatName]
            }}
          </view>
        </template>
      </view>
      <!-- 城市列表(搜索前) -->
      <view class="citys" v-if="!serachCity">
        <view
            v-for="(city, index) in sortItems"
            :key="index"
            v-show="city.isCity"
            class="citys-row"
        >
          <view
              class="citys-item-letter"
              :id="'city-letter-' + (city.name === '#' ? '0' : city.name)"
          >{{ city.name }}
          </view
          >
          <view
              class="citys-item"
              v-for="(item, inx) in city.citys"
              :key="inx"
              @click="cityTrigger(item)"
          >{{ item.cityName }}
          </view
          >
        </view>
      </view>
      <!-- 城市列表(搜索后)  -->
      <view class="citys" v-if="serachCity">
        <view
            v-for="(item, index) in searchDatas"
            :key="index"
            class="citys-row"
        >
          <view class="citys-item" :key="inx" @click="cityTrigger(item)">{{
              item.name
            }}
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 城市选择索引-->
    <view class="city-indexs-view" v-if="!serachCity">
      <view class="city-indexs">
        <view
            v-for="(cityIns, index) in handleCity"
            :class="{
            'city-indexs-text': toView != cityIns.forName,
            'city-indexs-text-select': toView == cityIns.forName,
          }"
            v-show="cityIns.isCity"
            :key="index"
            @click="cityindex(cityIns.forName)"
        >
          {{ cityIns.name }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import citySelect from './citySelect.js'

export default {
  props: {
    //查询提示文字
    placeholder: {
      type: String,
      default: '请输入城市名称',
    },
    //传入要排序的名称
    formatName: {
      type: String,
      default: 'cityName',
    },
    //当前定位城市
    activeCity: {
      type: Object,
      default: () => null,
    },
    //热门城市
    hotCity: {
      type: Array,
      default: () => [],
    },
    //城市数据
    obtainCitys: {
      type: Array,
      default: () => [],
    },
    hotelCitys: {
      type: Object,
      default: () => [],
    },
    //是否有搜索
    isSearch: {
      type: Boolean,
      default: true,
    },
  },
  data () {
    return {
      toView: 'city-letter-Find', //锚链接 初始值
      scrollTop: 0, //scroll-view 滑动的距离
      cityindexs: [], // 城市索引
      activeCityIndex: '', // 当前所在的城市索引
      handleCity: [], // 处理后的城市数据
      serachCity: '', // 搜索的城市
      cityData: [],
    }
  },
  computed: {
    /**
     * @desc 城市列表排序
     * @return  Array
     */
    sortItems () {
      for (let index = 0; index < this.handleCity.length; index++) {
        if (this.handleCity[index].isCity) {
          let cityArr = this.handleCity[index].citys
          cityArr = cityArr.sort(function (a, b) {
            var value1 = a.unicode
            var value2 = b.unicode
            return value1 - value2
          })
        }
      }
      return this.handleCity
    },
    /**
     * @desc 搜索后的城市列表
     * @return Array
     */
    searchDatas () {
      //这个比较耗时
      if (!this.serachCity && this.serachCity.length== 0) {
        return
      }
      var searchData = []
      for (let i = 0; i < this.cityData.length; i++) {
        if (this.cityData[i][this.formatName].indexOf(this.serachCity) !== -1) {
          searchData.push({
            oldData: this.cityData[i],
            name: this.cityData[i][this.formatName],
          })
        }
      }
      return searchData
    },
  },
  created () {
    // 初始化城市数据
    if (this.obtainCitys && this.obtainCitys.length > 0) {
      this.cityData = this.obtainCitys
    }
    if (this.cityData && this.cityData.length > 0) {
      this.initializationCity()
      this.buildCityindexs()
    }
  },
  watch: {
    obtainCitys (newData) {
      if (newData && newData.length > 0) {
        this.updateCitys(newData)
      }
    },
    hotelCitys: {
      handler (newData) {
        this.cityData = newData.cityData
        this.handleCity = newData.handleCity
        this.cityindexs = newData.cityindexs
      },
      immediate: true,
    },
  },
  methods: {
    /**
     * @desc 初始化
     */
    updateCitys (data) {
      if (data && data.length) {
        this.cityData = data
        this.initializationCity()
        this.buildCityindexs()
      }
    },
    updateHotelCitys (data) {
      let keys = Object.keys(data)
      for (let index = 0; index < keys.length; index++) {
        this.cityData = this.cityData.concat(data[keys[index]])
      }
      this.initHotelCity()
      //   this.buildCityindexs();
    },
    /**
     * @desc 监听输入框的值
     */
    keyInput (event) {
      this.serachCity = event.detail.value
    },
    initHotelCity () {
      this.handleCity = []
      const cityLetterArr = Object.keys(this.hotelCitys)
      this.cityindexs = []
      this.cityindexs = this.cityindexs.concat(cityLetterArr)
      for (let index = 0; index < cityLetterArr.length; index++) {
        this.handleCity.push({
          name: cityLetterArr[index],
          isCity: true, // 用于区分是否含有当前字母开头的城市
          citys: this.hotelCitys[cityLetterArr[index]].map((item) => {
            item.cityName = item.name
            item.pinyin = item.spell
            item.unicode = this.getLetter(item.name).unicode
            return item
          }), // 存放城市首字母含是此字母的数组
          forName:
              'city-letter-' +
              (cityLetterArr[index] == '#' ? '0' : cityLetterArr[index]), //label的绑定
        })
      }
    },
    /**
     * @desc 初始化城市数据
     * @return undefind
     */
    initializationCity () {
      this.handleCity = []
      const cityLetterArr = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        '#',
      ]
      for (let index = 0; index < cityLetterArr.length; index++) {
        this.handleCity.push({
          name: cityLetterArr[index],
          isCity: false, // 用于区分是否含有当前字母开头的城市
          citys: [], // 存放城市首字母含是此字母的数组
          forName:
              'city-letter-' +
              (cityLetterArr[index] == '#' ? '0' : cityLetterArr[index]), //label的绑定
        })
      }
    },
    /**
     * @desc 得到城市的首字母
     * @param str String
     */
    getLetter (str) {
      return citySelect.getFirstLetter(str[0])
    },
    /**
     * @desc 构建城市索引
     * @return undefind
     */
    buildCityindexs () {
      this.cityindexs = []
      for (let i = 0; i < this.cityData.length; i++) {
        // 获取首字母
        const cityLetter = this.getLetter(
            this.cityData[i][this.formatName]
        ).firstletter
        // 获取当前城市首字母的unicode，用作后续排序
        const unicode = this.getLetter(
            this.cityData[i][this.formatName]
        ).unicode
        const index = this.cityIndexPosition(cityLetter)
        if (this.cityindexs.indexOf(cityLetter) === -1) {
          this.handleCity[index].isCity = true
          this.cityindexs.push(cityLetter)
        }
        this.handleCity[index].citys.push({
          cityName: this.cityData[i][this.formatName],
          unicode: unicode,
          oldData: this.cityData[i],
        })
      }
    },
    /**
     * @desc 滑动到城市索引所在的地方
     * @param id String 城市索引
     */
    cityindex (id) {
      this.toView = id
      // //创建节点查询器
      // const query = uni.createSelectorQuery().in(this)
      // var that = this
      // that.scrollTop = 0
      // //滑动到指定位置(解决方法:重置到顶部，重新计算，影响:页面会闪一下)
      // setTimeout(() => {
      // 	query
      // 		.select('#city-letter-' + (id === '#' ? '0' : id))
      // 		.boundingClientRect(data => {
      // 			// console.log("得到布局位置信息" + JSON.stringify(data));
      // 			// console.log("节点离页面顶部的距离为" + data.top);
      // 			data ? (that.scrollTop = data.top) : void 0
      // 		})
      // 		.exec()
      // }, 0)
    },
    /**
     * @desc 获取城市首字母的unicode
     * @param letter String 城市索引
     */
    cityIndexPosition (letter) {
      if (!letter) {
        return ''
      }
      const ACode = 65
      return letter === '#' ? 26 : letter.charCodeAt(0) - ACode
    },
    /** @desc 城市列表点击事件
     *  @param Object
     */
    cityTrigger (item, type) {
      if (type == 'hot') {
        this.$emit('cityClick', item.oldData ? item.oldData : item)
      } else {
        // 传值到父组件
        this.$emit('cityClick', item.oldData ? item.oldData : item)
      }
    },
  },
}
</script>

<style lang="scss">
//宽度转换vw
@function vww($number) {
  @return ($number / 375) * 750 +rpx;
}

view {
  box-sizing: border-box;
}

.city-serach {
  color: #4a4a4a;
  padding: 30rpx 32rpx;
  display: flex;

  .search_content {
    width: 100%;
    display: flex;
    align-items: center;
    background: #f1f1f1;
    border-radius: 32rpx;
    padding: 0 32rpx;
    height: vww(34);
  }

  &-input {
    flex-grow: 1;
    height: vww(34);
    line-height: vww(34);
    font-size: vww(14);
    padding: 0 vww(5);
    padding-left: 20rpx;
    background: transparent;
  }
}

.city-select-main {
  position: relative;
  // overflow: scroll;
  // -webkit-overflow-scrolling: touch;
  width: 100%;
  height: 100%;
  background: #fff;
  // overflow-y: auto;
}

.city-select {
  position: relative;
  width: 100vw;
  height: calc(90vh - 110rpx);
  background: #fff;

  // 热门城市
  .hot-title {
    padding-left: 32rpx;
    width: 100vw;
    font-size: 14px;
    line-height: vww(40);
    color: #666666;
  }

  .hot-city {
    padding-left: 24rpx;
    padding-right: 24rpx;
    width: 100vw;
    display: flex;
    flex-wrap: wrap;

    .hot-item {
      width: auto;
      padding: 0 15rpx;
      height: 64rpx;
      line-height: 64rpx;
      font-size: 32rpx;
      text-align: center;
      color: #333333;
      background: #fff;
      border: 1px solid #e5e5e5;
      margin-left: 8rpx;
      margin-right: 8rpx;
      border-radius: 32rpx;
    }

    .hot-hidden {
      display: none;
      margin-right: 0;
    }
  }

  .citys {
    .citys-row {
      padding-left: vww(18);
      width: 100%;
      font-size: 14px;
      background: #fff;

      .citys-item-letter {
        margin-left: vww(-18);
        padding-left: vww(18);
        margin-top: -1px;
        width: 100vw;
        line-height: vww(30);
        color: #9b9b9b;
        background: #fff;
        border-top: none;
      }

      .citys-item {
        width: 100%;
        line-height: vww(50);
        color: #4a4a4a;
        border-bottom: 1px solid #ebebf0;

        &:last-child {
          border: none;
        }
      }
    }
  }

  .city-indexs-view {
    position: absolute;
    right: 12rpx;
    top: 0rpx;
    bottom: 0rpx;
    z-index: 999;
    display: flex;
    width: 40rpx;
    text-align: center;
    justify-content: center;
    align-items: center;

    .city-indexs {
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
      vertical-align: middle;
      align-self: center;
      display: flex;
      flex-direction: column;
      height: auto;

      .city-indexs-text {
        width: 40rpx;
        font-size: 24rpx;
        color: #666666;
      }

      .city-indexs-text-select {
        width: 40rpx;
        font-size: 24rpx;
        border-radius: 20rpx;
        color: white;
        background: #00b893;
      }
    }
  }
}
</style>
